package com.lecoboy.highconcurrency.threaddemo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 等待/通知机制模拟
 */
public class WaitNotify {
    static boolean flag = true;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread waitThread = new Thread(new Wait(), "WaitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyThread = new Thread(new Notify(), "NotifyThread");
        notifyThread.start();
    }

    /**
     * 使用wait、notify、notifyAll 时需要先对调用对象加锁
     */
    static class Wait implements Runnable {

        @Override
        public void run() {
            // 加锁，拥有lock的Monitor
            synchronized (lock) {
                //当条件不满足时，继续wait，同时释放了lock的锁
                while (flag) {
                    try {
                        System.out.println(Thread.currentThread() + " flag is true. wait@ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        // 调用wait() 线程状态由RUNNING 变为 WAITING,并将当前线程放置到对象的等待队列
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //条件满足时，完成工作
                System.out.println(Thread.currentThread() + " 当lock释放后输出 flag is false. wait@ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));

            }
        }
    }

    static class Notify implements Runnable {

        @Override
        public void run() {
            // 加锁，拥有lock的Monitor
            synchronized (lock) {
                //获取lock的锁，然后进行通知，通知时不会释放Lock的锁
                //直到当前线程释放了lock后，waitThread才能从wait方法中返回
                System.out.println(Thread.currentThread() + " 锁住 lockdemo . notify@ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));

                //notifyAll()将等待队列中所有线程全部移到同步队列，被移动的线程状态由WAITING变为BLOCKED
                //直到释放锁 才由BLOCKED变为RUNNING
                lock.notifyAll();
                flag = false;
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            //再次加锁
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " 再次锁住lock，释放后wait的线程才继续. sleep@ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));

            }
        }
    }

}
